package com.wwwarehouse.resource_center.fragment.createobject.createstore;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.flexbox.FlexboxLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.bean.map.NearAddressBean;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.bean.upload.FileUploadBean;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.eventbus_event.CardDeskEvent;
import com.wwwarehouse.common.eventbus_event.UploadSuccessEvent;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.bean.ImAbstractObjectBean;
import com.wwwarehouse.resource_center.bean.goods.GoodsAttributesBean;
import com.wwwarehouse.resource_center.bean.goods.GoodsSelectLabelBean;
import com.wwwarehouse.resource_center.bean.goods.RequestBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.AddressEvent;
import com.wwwarehouse.resource_center.eventbus_event.GoodsEvent;
import com.wwwarehouse.resource_center.eventbus_event.ImagePathEvent;
import com.wwwarehouse.resource_center.eventbus_event.RulesEvent;
import com.wwwarehouse.resource_center.eventbus_event.StringEvent;
import com.wwwarehouse.resource_center.fragment.createobject.creategoods.CreateGoodsFragment;
import com.wwwarehouse.resource_center.fragment.createobject.creategoods.GoodsAttributesProtectFragment;
import com.wwwarehouse.resource_center.fragment.createobject.creategoods.GoodsSelectTheLabelParentFragment;
import com.wwwarehouse.resource_center.fragment.createobject.creategoods.UploadPicFragment;
import com.wwwarehouse.resource_center.fragment.rules.TheParentFragment;
import com.wwwarehouse.resource_center.utils.UploadPicUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.resource_center.constant.ResourceConstant.PATH_CREATESTORE;

/**
 * Description: 创建商店
 * Copyright  : Copyright (c) 2017
 * Author     : yfwang
 * Date       : 2017/9/7 13:39
 */
@Route(path = PATH_CREATESTORE)
public class CreateStoreFragment extends TheParentFragment implements View.OnClickListener {


    RelativeLayout mStoreLable;
    public RelativeLayout mStoreName;
    public RelativeLayout mStorePicture;
    RelativeLayout mStoreDescribe;
    RelativeLayout mStoreAddress;
    RelativeLayout mStoreAttribute;

    public TextView mName;
    public TextView mAddress;
    public TextView mDes;
    public FlexboxLayout mLaber;
    public FlexboxLayout mAttr;
    public LinearLayout mLLLaber;
    public LinearLayout mLLPic;
    public ImageView mIvAttr;
    public ImageView mIvPic;
    public TextView mTvAttr;

    public ElasticScrollView elasticScrollView;
    public boolean isShowFinish = true;
    public String path;
    public ArrayList<GoodsSelectLabelBean.ListBean> data;
    public ArrayList<GoodsAttributesBean.ListBean> listBeen;
    public NearAddressBean nearAddressBean;
    public String ownerUkid;
    public TextView img_descrip;
    public File mFile;
    public FileUploadBean fileUploadBean;
    public String operationUkid;
    public String storeName;
    public String storeDes;
    public ImageView  no_pic ;
    public ImageView img_name ;
    public String abstractObjectUkid;
    public int pos;  //当前第几页
    @Override
    protected int getContentId() {
        return R.layout.fragment_create_store;
    }

    @Override
    protected void init(View view) {


        elasticScrollView = (ElasticScrollView) view.findViewById(R.id.goods_scroll);

        mStoreName = (RelativeLayout) view.findViewById(R.id.rel_name);
        mStorePicture = (RelativeLayout) view.findViewById(R.id.rel_picture);
        mStoreDescribe = (RelativeLayout) view.findViewById(R.id.rel_describe);
        mStoreAddress = (RelativeLayout) view.findViewById(R.id.rel_address);
        mStoreAttribute = (RelativeLayout) view.findViewById(R.id.rel_attribute);
        mStoreLable = (RelativeLayout) view.findViewById(R.id.rel_label);
        mLLLaber = (LinearLayout) view.findViewById(R.id.ll_laber);
        mLLPic = (LinearLayout) view.findViewById(R.id.ll_pic);
        mLaber = (FlexboxLayout) view.findViewById(R.id.fl_laber);
        mAttr = (FlexboxLayout) view.findViewById(R.id.fl_attr);
        img_descrip = findView(view,R.id.img_descrip);
        mIvAttr = (ImageView) view.findViewById(R.id.iv_attr);
        mIvPic = (ImageView) view.findViewById(R.id.iv_pic);
        mTvAttr = (TextView) view.findViewById(R.id.tv_attr);
        no_pic = findView(view,R.id.no_pic);
        img_name = findView(view,R.id.img_name);
        Bundle bundle = getArguments();
        try {
            CardDeskTaskResponseBean.TaskBean taskBean = (CardDeskTaskResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS);
            if (null!=taskBean){
                this.ownerUkid = taskBean.getBelongBusiness();
                this.operationUkid = taskBean.getCardUkid();
            }else {
                CardDeskFunctionResponseBean.TaskBean mBean = (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
                if (null!=mBean){
//                    this.operationUkid = mBean.getTaskTypeUkid();
                    this.ownerUkid = mBean.getBusinessId();
                }
            }

        } catch (Exception e) {

        }
        mIvAttr.setSelected(true);
        mTvAttr.setSelected(true);
        mStoreAttribute.setSelected(true);
        mStorePicture.setSelected(false);

        mName = (TextView) view.findViewById(R.id.tv_name);
        mAddress = (TextView) view.findViewById(R.id.tv_store_address);
        mDes = (TextView) view.findViewById(R.id.tv_des);
        mLLLaber.setVisibility(View.VISIBLE);
        mLLPic.setVisibility(View.VISIBLE);
        mIvPic.setVisibility(View.GONE);
        EventBus.getDefault().register(this);

        mStoreName.setOnClickListener(this);
        mStorePicture.setOnClickListener(this);
        mStoreDescribe.setOnClickListener(this);
        mStoreAddress.setOnClickListener(this);
        mStoreAttribute.setOnClickListener(this);
        mStoreLable.setOnClickListener(this);


        elasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                if (isShowFinish) {
                    ((BaseCardDeskActivity) mActivity).showTitleBt1();
                    ((BaseCardDeskActivity) mActivity).setTitleBt1Text(R.string.complete);
                    boolean verification = verification();
                    if (verification) {
                        ((BaseCardDeskActivity) mActivity).setTitleBt1Enable(true);
                    } else {
                        ((BaseCardDeskActivity) mActivity).setTitleBt1Enable(false);
                    }

                } else {
                    ((BaseCardDeskActivity) mActivity).hideTitleBt();
                }
                isShowFinish = !isShowFinish;
            }


            @Override
            public void onUpPull() {
            }
        });

    }
    @Override
    public void titleBt1Click() {
        if (peekFragment() instanceof CreateStoreFragment){
            if (path != null && !path.isEmpty()) {
                showProgressDialog("图片上传中...");
                UploadPicUtil.getInstance().uploadPic(path, mFile, getActivity());
            } else {
                request(ResourceConstant.SAVE_OBJECT,"");
            }
        }
    }
    public void request(String url, String cardType) {
        try {
            Map<String, Object> map = new HashMap<>();

            //标签列表
            List<RequestBean> labelList = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                RequestBean labelBean = new RequestBean();
                labelBean.setLabelUkid(data.get(i).getLabelUkid() + "");
                labelList.add(labelBean);
            }

            //属性列表
            List<RequestBean> attributeList = new ArrayList<>();

            for (int i = 0; i < listBeen.size(); i++) {
                RequestBean attributeBean = new RequestBean();
                attributeBean.setAttributeUkid(listBeen.get(i).getAttributeUkid() + "");
                attributeBean.setAttributeValue(listBeen.get(i).getAttributeValue());
                attributeList.add(attributeBean);
            }

            //地址
            RequestBean cmAddressBean = new RequestBean();
            cmAddressBean.setAddress(nearAddressBean.getAddress());
            cmAddressBean.setCity(nearAddressBean.getCity());
            cmAddressBean.setCountry("中国");
            cmAddressBean.setDistrict(nearAddressBean.getCounty());
            cmAddressBean.setProvince(nearAddressBean.getProvince());

            //坐标点
            RequestBean gsMapPointBean = new RequestBean();
            gsMapPointBean.setX(nearAddressBean.getxOffset());
            gsMapPointBean.setY(nearAddressBean.getxOffset());
            gsMapPointBean.setZ("0");

            ImAbstractObjectBean imAbstractObjectBean = new ImAbstractObjectBean();

            //媒体列表
            if (fileUploadBean != null) {
                List<RequestBean> mediaList = new ArrayList<>();
                RequestBean mediaBean = new RequestBean();
                mediaBean.setMediaName(fileUploadBean.getData().get(0).getName());
                mediaBean.setMediaType("0");
                mediaBean.setRelatedUrl(fileUploadBean.getData().get(0).getPath());
                mediaList.add(mediaBean);
                imAbstractObjectBean.setMediaList(mediaList); //媒体列表

            }
            if (!TextUtils.isEmpty(abstractObjectUkid)) {
                imAbstractObjectBean.setAbstractObjectUkid(abstractObjectUkid);
            }
            imAbstractObjectBean.setType("CREATE_H_SHOP");  //1-商品、2-工具、3-店铺、4-仓库
            imAbstractObjectBean.setName(mName.getText().toString().trim());  //物的名称
            imAbstractObjectBean.setLabelList(labelList);  //标签列表
            imAbstractObjectBean.setIntroduction(mDes.getText().toString().trim());
            imAbstractObjectBean.setAttributeList(attributeList);  //属性列表
            imAbstractObjectBean.setOwnerUkid(ownerUkid);       //业务单位UKid
            imAbstractObjectBean.setCmAddress(cmAddressBean);     //地址
            imAbstractObjectBean.setGsMapPoint(gsMapPointBean);   //坐标点
            map.put("imAbstractObject", imAbstractObjectBean);
            if (operationUkid != null && !operationUkid.isEmpty()) {
                map.put("operationUkid", operationUkid); //任务UKID
            }
            if (!TextUtils.isEmpty(cardType)) {
                map.put("cardType", cardType);
            }
            httpPost(url, map, 0, true, "");
        } catch (Exception e) {
            LogUtils.showLog("店铺信息保存失败!");
        }


    }

    boolean verification() {

        boolean b = false;
        try {
            //验证保存信息
            String name = mName.getText().toString(); //名称
            String des = mDes.getText().toString(); //描述
            String address = mAddress.getText().toString(); //地址
            if (!name.isEmpty() && !des.isEmpty() && data != null && !data.isEmpty() && listBeen != null && !listBeen.isEmpty() && !address.isEmpty())
                b = true;
            if (getString(R.string.store_name).equals(name)) {
                b = false;
            }
            if (getString(R.string.goods_describe).equals(des)){
                b = false;
            }
        } catch (Exception e) {
            b = false;
        }
        return b;


    }

    public void onEventMainThread(Object event) {

        if (event instanceof StringEvent && "create_store_name".equals(((StringEvent) event).getFrom())) {
            storeName = ((StringEvent) event).getMsg();
            mName.setText(((StringEvent) event).getMsg());
            popFragment();
        } else if (event instanceof ImagePathEvent) {
            //显示图片
            path = ((ImagePathEvent) event).getMsg();
            mFile = ((ImagePathEvent) event).getmFile();
            mLLPic.setVisibility(View.GONE);
            mIvPic.setVisibility(View.VISIBLE);
            mStorePicture.setSelected(true);
            ImageLoader.getInstance().displayImage("file://" + ((ImagePathEvent) event).getMsg(), mIvPic);

        } else if (event instanceof AddressEvent) {
            nearAddressBean = ((AddressEvent) event).getNearAddressBean();
            mAddress.setText(nearAddressBean.getAddress());
            popFragment();
        } else if (event instanceof StringEvent && "descrip".equals(((StringEvent) event).getFrom())) {
            storeDes = ((StringEvent) event).getMsg();
            mDes.setText(((StringEvent) event).getMsg());
            popFragment();
        } else if (event instanceof GoodsEvent && ((GoodsEvent) event).getCode() == GoodsEvent.GOODS_LABEL_SELECT_NOTICE) {
            //标签
            try {
                data = new ArrayList<>();
                ArrayList<GoodsSelectLabelBean.ListBean> dataList = (ArrayList<GoodsSelectLabelBean.ListBean>) ((GoodsEvent) event).getData();
                data.addAll(dataList);
                setLaber(data);

            } catch (Exception e) {

            }


        } else if (event instanceof RulesEvent && GoodsEvent.GOODS_ATTRIBUTE_SELECT_NOTICE == ((RulesEvent) event).getCode()) {
            try {
                listBeen = (ArrayList<GoodsAttributesBean.ListBean>) ((RulesEvent) event).getData();
                setAttributes(listBeen);


            } catch (Exception e) {

            }


        } else if (event instanceof UploadSuccessEvent) {
            dismissProgressDialog();
            fileUploadBean = ((UploadSuccessEvent) event).getFileUploadBean();
            if (!TextUtils.isEmpty(abstractObjectUkid)) {
                request(ResourceConstant.UPDATE_ABSTRACT_OBJECT,"UPDATE_H_SHOP");
            }else {
                request(ResourceConstant.SAVE_OBJECT, "");
            }
        } else if (event instanceof BackListenerEvent) {

            if ("CreateStoreFragment".equals(((BackListenerEvent) event).getMsg())){
                DialogTools.getInstance().showTCDialog(getContext(), "提示", "返回将不会保存当前编辑内容，确定返回吗？", "再看看", "返回", null, new DialogTools.DismissListener() {
                    @Override
                    public void setDismissListener(Dialog dialog, View view) {
                        dialog.dismiss();
                        popFragment();
                    }
                });
            }
        }
    }

    public void setAttributes(ArrayList<GoodsAttributesBean.ListBean> listBeen) {
        mAttr.removeAllViews();
        mTvAttr.setVisibility(View.GONE);
        if (listBeen.size() >= 4) {
            for (int i = 0; i < 4; i++) {
                TextView textView = new TextView(getContext());
//                        textView.setWidth(ConvertUtils.dip2px(getContext(), 100));
                textView.setWidth(ConvertUtils.dip2px(getContext(), 100));
                textView.setTextColor(Color.parseColor("#FFFFFF"));
                textView.setTextSize(12);
                textView.setGravity(Gravity.CENTER_VERTICAL);
                textView.setMaxLines(1);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(0, ConvertUtils.dip2px(getContext(), 10), 0, 0);
                textView.setLayoutParams(layoutParams);
                textView.setText(listBeen.get(i).getAttributeName() + ": " + listBeen.get(i).getAttributeValue());
                mAttr.addView(textView);
            }
        } else {
            for (int i = 0; i < listBeen.size(); i++) {
                TextView textView = new TextView(getContext());
                textView.setWidth(ConvertUtils.dip2px(getContext(), 100));
//                        textView.setHeight(ConvertUtils.dip2px(getContext(), 100));
                textView.setTextColor(Color.parseColor("#FFFFFF"));
                textView.setTextSize(12);
                textView.setGravity(Gravity.CENTER_VERTICAL);
                textView.setMaxLines(1);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(0, ConvertUtils.dip2px(getContext(), 10), 0, 0);
                textView.setLayoutParams(layoutParams);
                textView.setText(listBeen.get(i).getAttributeName() + ": " + listBeen.get(i).getAttributeValue());
                mAttr.addView(textView);

            }
        }
    }

    public void setLaber(ArrayList<GoodsSelectLabelBean.ListBean> data) {
        mLaber.removeAllViews();
        mLLLaber.setVisibility(View.GONE);
        if (data.size() < 6) {
            for (int i = 0; i < data.size(); i++) {
                TextView textView = getTextView();

                textView.setTextColor(Color.parseColor("#337CFF"));
                textView.setText(data.get(i).getLabelName());
                textView.setBackgroundResource(R.drawable.laber_bg_selector);
                textView.setSelected(true);
                mLaber.addView(textView);
            }
            for (int i = 0; i < 6 - data.size(); i++) {
                TextView textView = getTextView();
                textView.setBackgroundResource(R.drawable.laber_bg_selector);
                textView.setSelected(false);
                mLaber.addView(textView);
            }
        } else if (data.size() >= 6) {
            for (int i = 0; i <= 5; i++) {
                TextView textView = new TextView(getContext());
                textView.setWidth(ConvertUtils.dip2px(getContext(), 80));
                textView.setHeight(ConvertUtils.dip2px(getContext(), 24));
                textView.setBackgroundResource(R.drawable.laber_bg_selector);
                textView.setTextColor(Color.parseColor("#337CFF"));
                textView.setTextSize(11);
                textView.setGravity(Gravity.CENTER);
                textView.setMaxLines(1);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                if (i == 5) {
                    textView.setText(R.string.ellipsis);
                } else {
                    textView.setText(data.get(i).getLabelName());
                }
                textView.setSelected(true);
                FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(ConvertUtils.dip2px(getContext(), 10), ConvertUtils.dip2px(getContext(), 8), 0, 0);
                textView.setLayoutParams(layoutParams);
                mLaber.addView(textView);
            }

        }
    }

    @NonNull
    TextView getTextView() {
        TextView textView = new TextView(getContext());
        textView.setWidth(ConvertUtils.dip2px(getContext(), 82));
        textView.setHeight(ConvertUtils.dip2px(getContext(), 26));
        textView.setBackgroundResource(R.drawable.laber_bg_selector);
        textView.setMaxLines(1);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(12);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(ConvertUtils.dip2px(getContext(), 10), ConvertUtils.dip2px(getContext(), 8), 0, 0);
        textView.setLayoutParams(layoutParams);
        return textView;
    }


    @Override
    public void setTitle() {
        if (peekFragment() instanceof CreateStoreFragment){
            mActivity.setTitle(R.string.create_store);
        }
    }

    @Override
    public void requestDatas() {

    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        try {

            if (what == 0) {
                if (TextUtils.equals("0", commonClass.getCode())) {
                    EventBus.getDefault().post(new GoodsEvent(GoodsEvent.GOODS_MODIFY,pos));
                    EventBus.getDefault().post(new CardDeskEvent("clear_back_stack"));
                } else {
                    toast(commonClass.getMsg());
                }
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onReLoad(int code) {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        initState();
        if (i == R.id.rel_name) {
            //店铺名称
            StoreAddNameFragment storeAddNameFragment = new StoreAddNameFragment();
            Bundle name = new Bundle();
            name.putString("name",storeName);
            storeAddNameFragment.setArguments(name);
            pushFragment(storeAddNameFragment);
        } else if (i == R.id.rel_picture) {
            //图片
            UploadPicFragment uploadPicFragment = new UploadPicFragment();
            Bundle bundle = new Bundle();
            if (null!=fileUploadBean){
                try {
                    bundle.putString("path", fileUploadBean.getData().get(0).getPath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                bundle.putString("path", path);
            }
            uploadPicFragment.setArguments(bundle);
            pushFragment(uploadPicFragment);

        } else if (i == R.id.rel_address) {
            //店铺地址
            StoreAddressFragment storeAddressFragment = new StoreAddressFragment();
            if (nearAddressBean != null) {
                Bundle b = new Bundle();
                b.putSerializable("address", nearAddressBean);
                storeAddressFragment.setArguments(b);
            }
            pushFragment(storeAddressFragment);
        } else if (i == R.id.rel_describe) {
            //描述
            StoreDescripFragment storeDescripFragment = new StoreDescripFragment();
            Bundle b = new Bundle();
            b.putString("des",storeDes);
            storeDescripFragment.setArguments(b);

            pushFragment(storeDescripFragment);

        } else if (i == R.id.rel_label) {
            //标签
            sp.putValue("businessId", ownerUkid);
            GoodsSelectTheLabelParentFragment  fragment = new GoodsSelectTheLabelParentFragment();
            Bundle b = new Bundle();
            b.putParcelableArrayList("LabelList",data);
            fragment.setArguments(b);
            pushFragment(fragment);
        } else if (i == R.id.rel_attribute) {
            //属性
            GoodsAttributesProtectFragment goodsAttributesSelectParentFragment = new GoodsAttributesProtectFragment();
            Bundle bundle = new Bundle();
            bundle.putString("categoryUkid", "");
            bundle.putParcelableArrayList("AttributeList",listBeen);
            goodsAttributesSelectParentFragment.setArguments(bundle);
            pushFragment(goodsAttributesSelectParentFragment);
        }


    }


    void initState() {
        ((BaseCardDeskActivity) mActivity).hideTitleBt();
        isShowFinish = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        initState();
        EventBus.getDefault().unregister(this);
    }

}
